package com.nhh.v.service

import com.nhh.exception.ServiceException
import com.nhh.v.cons.ServerCons
import com.nhh.v.dto.HomeUserInfo
import com.nhh.v.mapper.{NhhwakTownsMapper, NhhwakUsersMapper}
import com.nhh.v.model.NhhwakUsers
import com.nhh.v.utils.NhhUtil._
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
  * Created by ywp on 2018/9/4.
  */
@Service
class UsersService(@Autowired val nhhwakUsersMapper: NhhwakUsersMapper,
                   @Autowired val nhhwakTownsMapper: NhhwakTownsMapper) {

  def getUserById(uid: String): HomeUserInfo = {

    val user = nhhwakUsersMapper.selectUserById(uid.toInt)
    val homeUserInfo = new HomeUserInfo()
    //todo 数据类型不一致 set/get
    BeanUtils.copyProperties(user, homeUserInfo)
    val townRoleFm = user.getTownRole match {
      case "lord" ⇒ "城主"
      case "people" ⇒ "城民"
      case _ ⇒ "游民"
    }
    val townName = user.getTownId match {
      case tId if tId > 0 ⇒ nhhwakTownsMapper.selectTownNameById(user.getTownId.toString)
      case _ ⇒ "无"
    }

    homeUserInfo.setTownRoleFm(townRoleFm)
    homeUserInfo.setTownName(townName)
    homeUserInfo

  }


  def getHashRateInfo(uid: Integer): NhhwakUsers = {
    nhhwakUsersMapper.selectHashRateInfo(uid)
  }

  def getUserCount(status: Int = 0): Long = {
    nhhwakUsersMapper.selectCountByStatus(status)
  }

  @Transactional
  def updateNickname(nickname: String, uId: String): Unit = {
    nhhwakUsersMapper.updateNickname(uId, nickname)
  }

  @Transactional
  def updateUserCoins(uid: Integer, coinNums: BigDecimal): Unit = {
    nhhwakUsersMapper.updateUserCoins(uid, coinNums.bigDecimal)
  }

  def getUser(uId: String): GetUserInfo = {
    val user = getUserById(uId)
    val userInfo = UserInfo()
    //todo 对象属性拷贝需要确认
    BeanUtils.copyProperties(user, userInfo)
    Option(user) match {
      case None ⇒ throw new ServiceException("4100", "用户信息获取失败")
      case _ ⇒

        userInfo.setHeadimgurl(getHeadImgUrl(user))
        userInfo.copy(nhhcoins = formatNHH(BigDecimal(user.getNhhcoins)))
        val inviter = Inviter()
        if (user.getInviter > 0) {
          val nickname = nhhwakUsersMapper.selectNickname(user.getInviter.toString)
          userInfo.copy(inviterName = nickname)
          inviter.copy(nickname)
        }
        val shareUrl = s"${ServerCons.RESURL}download/spd?userNo=${user.getUserNo}"
        GetUserInfo(user = userInfo, inviter = inviter, shareUrl = shareUrl)
    }
  }

  def getInviteUserNumById(uid: Integer): Integer = {
    nhhwakUsersMapper.getInviteUserNumById(uid)
  }
}


case class GetUserInfo(user: UserInfo, inviter: Inviter, shareUrl: String) extends ResultData

case class UserInfo(nhhcoins: String = "", inviterName: String = "") extends HomeUserInfo

case class Inviter(nickname: String = "无")